package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 虎哥
 */
@Service
public class UploadService {

    private static final String BASE_IMAGE_DIR = "C:\\lesson\\heima83\\nginx-1.12.2\\html\\images";
    private static final String BASE_IMAGE_URL = "http://image.leyou.com/images/";

    public String uploadImage(MultipartFile file) {
        // 获取文件名称
        String filename = file.getOriginalFilename();

        // 获取文件路径
        String extension = "." + StringUtils.substringAfterLast(filename, ".");
        filename = UUID.randomUUID().toString() + extension;
        File path = new File(BASE_IMAGE_DIR, filename);

        // 保存图片
        try {
            file.transferTo(path);
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }

        // 返回图片的地址
        return BASE_IMAGE_URL + filename;
    }

    @Autowired
    private OSSProperties prop;

    @Autowired
    private OSS client;

    public Map<String, Object> getSignature() {
        try {
            // 1.生成签名
            // 1.1.过期时间策略
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // 1.2.文件限制策略
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            // 1.3.对策略加密
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 1.4.生成签名
            String postSignature = client.calculatePostSignature(postPolicy);

            // 2.封装返回结果
            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
